// 展开/折叠功能
document.addEventListener('click', function(e) {
    const icon = e.target.closest('.toggle-icon');
    if (!icon) return;

    const row = icon.closest('tr[data-id]');
    if (!row) return;

    const isExpanding = icon.textContent.trim() === '+';
    icon.textContent = isExpanding ? '-' : '+';

    if (isExpanding) {
        // 展开逻辑：只显示直接子级
        const immediateChildren = document.querySelectorAll(`tr[data-parent="${row.dataset.id}"]`);
        immediateChildren.forEach(child => {
            child.style.display = 'table-row';
        });
    } else {
        // 折叠逻辑：收起所有子级（包括多级嵌套）
        collapseAllDescendants(row.dataset.id);
    }
});

// 递归收起所有子孙部门
function collapseAllDescendants(parentId) {
    const children = document.querySelectorAll(`tr[data-parent="${parentId}"]`);
    children.forEach(child => {
        // 隐藏当前层级
        child.style.display = 'none';

        // 递归隐藏子级
        collapseAllDescendants(child.dataset.id);

        // 将子级的图标状态重置为+
        const childIcon = child.querySelector('.toggle-icon');
        if (childIcon) childIcon.textContent = '+';
    });
}

// 全部展开（修正：移出嵌套，改为独立监听）
document.getElementById('expandAllBtn').addEventListener('click', function() {
    document.querySelectorAll('.toggle-icon').forEach(icon => {
        icon.textContent = '-';
    });
    document.querySelectorAll('.sub-department-row').forEach(row => {
        row.style.display = 'table-row';
    });
});

// 全部折叠（修正：移出嵌套，改为独立监听）
document.getElementById('collapseAllBtn').addEventListener('click', function() {
    document.querySelectorAll('.toggle-icon').forEach(icon => {
        icon.textContent = '+';
    });
    document.querySelectorAll('.sub-department-row').forEach(row => {
        row.style.display = 'none';
    });
});

// 显示Flash消息（新增）
function showFlashMessage(message, isSuccess) {
    const messageDiv = document.createElement('div');
    messageDiv.className = isSuccess ? 'flash-message success' : 'flash-message error';
    messageDiv.textContent = message;

    document.querySelector('.module-header').after(messageDiv);

    // 3秒后自动消失
    setTimeout(() => {
        messageDiv.remove();
    }, 5000);
}

// 检查并显示页面加载时的Flash消息（新增）
document.addEventListener('DOMContentLoaded', function() {
    // 先移除Thymeleaf的原生消息元素（不等待）
    document.querySelectorAll('[data-flash-error], [data-flash-success]').forEach(msg => {
        // 在移除前先显示对应的样式化消息
        const isSuccess = msg.hasAttribute('data-flash-success');
        showFlashMessage(msg.textContent, isSuccess);
        msg.remove(); // 立即移除原生消息
    });
    // 检查是否有Flash消息
    const successMessage = document.querySelector('[data-flash-success]');
    const errorMessage = document.querySelector('[data-flash-error]');

    if (successMessage) {
        showFlashMessage(successMessage.textContent, true);
    }
    if (errorMessage) {
        showFlashMessage(errorMessage.textContent, false);
    }
});

// 保存当前展开状态
function saveExpandedState() {
    const expandedIds = [];
    document.querySelectorAll('.toggle-icon').forEach(icon => {
        if (icon.textContent.trim() === '-') {
            expandedIds.push(icon.closest('tr').dataset.id);
        }
    });
    sessionStorage.setItem('deptExpandedState', JSON.stringify(expandedIds));
}

// 恢复展开状态
function restoreExpandedState() {
    const savedState = sessionStorage.getItem('deptExpandedState');
    if (savedState) {
        JSON.parse(savedState).forEach(id => {
            const icon = document.querySelector(`tr[data-id="${id}"] .toggle-icon`);
            if (icon) {
                icon.textContent = '-';
                document.querySelectorAll(`tr[data-parent="${id}"]`).forEach(child => {
                    child.style.display = 'table-row';
                });
            }
        });
    }
}

// 修改POST请求处理（简化版）
document.addEventListener('DOMContentLoaded', function() {
    // 页面加载时恢复状态
    restoreExpandedState();

    document.body.addEventListener('click', function(event) {
        if (event.target.matches('a[data-method="post"]')) {
            event.preventDefault();

            // 保存当前展开状态
            saveExpandedState();

            // 直接提交表单（无CSRF）
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = event.target.getAttribute('href');
            document.body.appendChild(form);
            form.submit();
        }
    });
});

document.addEventListener('DOMContentLoaded', function() {
    // 获取弹窗元素
    const modal = document.getElementById('setHeadModal');
    const closeBtn = document.querySelector('.close');
    const cancelBtn = document.querySelector('.cancel-btn');
    const form = document.getElementById('setHeadForm');
    const headSelect = document.getElementById('headSelect');

    // 打开弹窗
    document.querySelectorAll('.set-head').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            const deptId = this.getAttribute('href').split('/').pop();
            document.getElementById('departmentId').value = deptId;

            fetch(`/department/set-head/${deptId}/candidates`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(users => {
                    headSelect.innerHTML = '<option value="">-- 请选择 --</option>';
                    users.forEach(user => {
                        const option = document.createElement('option');
                        option.value = user.userId;
                        option.textContent = `${user.realName || user.username} (${user.username})`;
                        headSelect.appendChild(option);
                    });
                    modal.style.display = 'block';
                })
                .catch(error => {
                    console.error('获取负责人候选列表失败:', error);
                    alert('获取负责人候选列表失败: ' + error.message);
                });
        });
    });

    // 关闭弹窗
    function closeModal() {
        modal.style.display = 'none';
    }

    closeBtn.onclick = closeModal;
    cancelBtn.onclick = closeModal;

    // 点击弹窗外部关闭
    window.onclick = function(event) {
        if (event.target === modal) {
            closeModal();
        }
    };

    // 设置负责人表单提交
    document.getElementById('setHeadForm').addEventListener('submit', function(e) {
        e.preventDefault();

        const formData = new FormData(this);
        const deptId = document.getElementById('departmentId').value;

        fetch(`/department/set-head/${deptId}`, {
            method: 'POST',
            body: new URLSearchParams(formData)
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    modal.style.display = 'none';
                    // 可选：刷新页面或更新UI
                    location.reload();
                } else {
                    alert(data.message);
                }
            })
            .catch(error => {
                console.error('设置负责人失败:', error);
                alert('设置负责人失败，请稍后重试');
            });
    });
});

// 保持其他原有方法不变
function exportDepartments() {
    window.open('/api/department/export', '_blank');
}

function adjustHierarchy() {
    alert('调整部门层级功能将在后续实现');
}

function mergeDepartments() {
    alert('部门合并功能将在后续实现');
}